<template>
  <el-drawer
      v-model="props['show']"
      :before-close="beforeClose"
      direction="ltr"
      @closed="emit('close')"
  >
    <div v-if="props['mode']===0">
      <el-radio-group v-model="page" style="margin-bottom: 30px">
        <el-radio-button label="edit">编辑</el-radio-button>
        <el-radio-button label="trans">调动</el-radio-button>
      </el-radio-group>
      <div v-if="page==='edit'">
        <el-form
            ref="formEmp"
            :model="empForm"
            :rules="rules"
            label-position="left"
            label-width="200px"
        >
          <el-form-item label="Name" prop="name">
            <el-input v-model="empForm.name"/>
          </el-form-item>
          <el-form-item label="Status" prop="status">
            <el-select v-model="empForm.status">
              <el-option label="在职" value="在职"></el-option>
              <el-option label="兼职" value="兼职"></el-option>
              <el-option label="试用" value="试用"></el-option>
              <el-option label="离职" value="离职"></el-option>
              <el-option label="返聘" value="返聘"></el-option>
              <el-option label="退休" value="退休"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="position" prop="position">
            <el-input v-model="empForm.position"/>
          </el-form-item>

          <el-button
              :loading="empLoading"
              :style="{marginTop: '80px'}"
              type="primary"
              @click="submit(formEmp)"
          >submit
          </el-button>
        </el-form>
      </div>
      <div v-else>
        <el-form
            ref="formEmp"
            :model="empForm"
            :rules="rules"
            label-position="left"
            label-width="200px"
        >
          <el-form-item label="transferDate" prop="arriveDate">
            <el-date-picker
                v-model="empForm.arriveDate"
                type="date"
            />
          </el-form-item>
          <el-form-item label="new department" prop="departmentId">
            <el-select v-model="empForm.departmentId">
              <el-option
                  v-for="dep in allDepInfo"
                  :label="dep.name" :value='dep.departmentId'/>

            </el-select>
          </el-form-item>
          <el-form-item label="Job" prop="job">
            <el-input v-model="empForm.job"/>
          </el-form-item>
          <el-form-item label="result" prop="why">
            <el-input v-model="empForm.why"/>
          </el-form-item>
          <el-button
              :loading="empLoading"
              :style="{marginTop: '80px'}"
              type="primary"
              @click="submit(formEmp)"
          >submit
          </el-button>
        </el-form>
      </div>
    </div>
    <div v-else-if="props['mode']===1">

    </div>
  </el-drawer>
</template>

<script setup>
import {ElDrawer, ElNotification} from "element-plus";
import {onUpdated, reactive, ref} from "vue";
import axios from "axios";
import {getAllDepartment} from "../../util";
import {useRoute} from "vue-router";


const props = defineProps(["show", "mode", "data"])
const emit = defineEmits(["close", "refreshData", "changeData"])
const page = ref("edit")
const formEmp = ref(null)
const beforeClose = ref((done) => {
  done()
})
const empLoading = ref(false)
const depLoading = ref(false)
const route = useRoute()
const type = ref('')

let map = new Map()
map.set("在职", 1)
map.set("兼职", 2)
map.set("试用", 3)
map.set("离职", 4)
map.set("返聘", 5)
map.set("退休", 6)
const map2 = ["在职", "兼职", "试用", "离职", "返聘", "退休"]
let map3 = new Map()
map3.set("edit", "updateEmp")
map3.set("trans", "transEmp")
const allDepInfo = ref([])

onUpdated(async () => {
  allDepInfo.value = await getAllDepartment(route.query.token)
})


let empFormData = {
  id: -1,
  name: null,
  status: null,
  arriveDate: null,
  position: null,
  job: null,
  departmentId: -1,
  why: ''
}
onUpdated(() => {
  empForm.value = Object.assign({why: ''}, props["data"])
})
const empForm = ref(empFormData)
const submit = async (form) => {
  switch (props["mode"]) {
    case 0: {
      empLoading.value = true
      break;
    }
    case 1: {
      depLoading.value = true
      break;
    }

  }
  let res = await new Promise((resolve) => {
    form.validate(res => {
      resolve(res)
    })
  })
  if (res === true) {
    let data = {
      id: empForm.value.id,
      name: empForm.value.name,
      status: map.get(empForm.value.status),
      position: empForm.value.position,
      job: empForm.value.job,
      arriveDate: empForm.value.arriveDate instanceof Date ? empForm.value.arriveDate.toISOString().slice(0, 10) : empForm.value.arriveDate,
      departmentId: empForm.value.departmentId,
      why: empForm.value.why
    }
    try {
      await new Promise((resolve, reject) => {
        axios.post(import.meta.env.VITE_APP_BASE_URL + "/api/" + map3.get(page.value) + "?token=" + route.query.token, JSON.stringify(data), {
          timeout: 1000,
          headers: {
            "Content-Type": "applications/json",
          },
        }).then(res => {
          if (res.status !== 200) {
            reject(res.status)
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
      ElNotification({
        title: 'success',
        message: 'update successfully',
      })
    } catch (e) {
      ElNotification({
        title: 'error',
        message: 'unknown error happen:' + e,
      })
    } finally {
      switch (props["mode"]) {
        case 0:
          empLoading.value = false
          break;
        case 1:
          depLoading.value = false
          break;
      }
      beforeClose.value = done => {
        done()
      }
      data.status = map2[data.status - 1]
      emit("changeData", data)
      emit("refreshData")
    }

  }
}
const rules = reactive({
  name: [
    {
      required: true,
      message: "please input name",
      trigger: "blur",
    },
  ],
  status: [
    {
      type: "string",
      required: true,
      message: "please input status",
      trigger: "change"
    }
  ],
  arriveDate: [
    {
      type: 'date',
      required: true,
      message: "please input arriveDate",
      trigger: 'change',
    },
  ],
  position: [
    {
      required: true,
      message: "please input workplace",
      trigger: "blur"
    }
  ],
  job: [
    {
      required: true,
      message: "please input job",
      trigger: "blur"
    }
  ],
  departmentId: [
    {
      // type:"string",
      required: true,
      message: "please select",
      trigger: "change"
    }
  ]
})
</script>

<style scoped>

</style>